package com.xzh.mallorderapi.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzh.mallorderapi.dao.OrderMapper;
import com.xzh.mallorderapi.service.CartItemFeignService;
import com.xzh.mallorderapi.util.XinUtils;
import com.xzh.mallorderspi.model.Order;
import com.xzh.mallorderspi.model.OrderItem;
import com.xzh.mallorderspi.model.search.OrderSeaechBean;
import com.xzh.mallorderspi.model.search.Sales;
import com.xzh.mallorderspi.service.OrderItemService;
import com.xzh.mallorderspi.service.OrderService;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;


import org.apache.seata.spring.annotation.GlobalTransactional;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    private OrderMapper orderMapper;
    private Snowflake snowflake;
    private OrderItemService orderItemService;
    private CartItemFeignService cartItemFeignService;
    private RedisTemplate<String, Object> redisTemplate;
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    public void setOrderMapper(OrderMapper orderMapper) {
        this.orderMapper = orderMapper;
    }

    @Autowired
    public void setSnowflake(Snowflake snowflake) {
        this.snowflake = snowflake;
    }

    @Autowired
    public void setOrderItemService(OrderItemService orderItemService) {
        this.orderItemService = orderItemService;
    }

    @Autowired
    public void setCartItemFeignService(CartItemFeignService cartItemFeignService) {
        this.cartItemFeignService = cartItemFeignService;
    }

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Autowired
    public void setRocketMQTemplate(RocketMQTemplate rocketMQTemplate) {
        this.rocketMQTemplate = rocketMQTemplate;
    }


    // 查询所有的订单，不查询订单项
    @Override
    public Page<Order> findAll(OrderSeaechBean osb, Page<Order> page) {
        return orderMapper.findAll(osb, page);
    }
    // 查询唯一订单
    @Override
    public Order findById(Integer id) {
        return orderMapper.selectById(id);
    }

    @Override
    public Order findByOrderNo(String orderNo) {
        return orderMapper.findByOrderNo(orderNo);
    }

    @Override
    public Order findBySeckillNo(String seckillNo) {
        return orderMapper.findBySeckillNo(seckillNo);
    }

    @GlobalTransactional(rollbackFor = Exception.class,propagation = org.apache.seata.tm.api.transaction.Propagation.REQUIRES_NEW)
    @Override
    public boolean save(Order order) {
        String orderNo = snowflake.nextIdStr();
        order.setOrderNo(orderNo);

        List<Integer> carIteamIds = new ArrayList<>();
        // 订单的总价格
        BigDecimal totalPay = BigDecimal.ZERO;
        if(XinUtils.isNotEmpty(order.getOrderItems())){
            for(OrderItem ot:order.getOrderItems()){
                if(ot.getId()!=null){
                    carIteamIds.add(ot.getId());
                }
                BigDecimal toPrice = ot.getDealPrice().multiply(new BigDecimal(ot.getCount()));
                totalPay = totalPay.add(toPrice);
            }
        }
        totalPay = totalPay.setScale(2, RoundingMode.HALF_DOWN);
        order.setTotalPay(totalPay);
        // 改变订单的状态
        if(XinUtils.isEmpty(order.getStatus())){
            order.setStatus("待支付");
        }
        order.setCheckoutTime(LocalDateTime.now());
        // 保存订单
        int count = orderMapper.insert(order);
        if(count>0 && XinUtils.isNotEmpty(order.getOrderItems())){
            for(OrderItem ot:order.getOrderItems()){
                Integer orderId = order.getId();
                for(OrderItem ot1:order.getOrderItems()){
                    ot1.setId(null);
                    ot1.setOrderId(orderId);
                    orderItemService.save(ot1);
                }
            }
        }

        if(!carIteamIds.isEmpty()){
            cartItemFeignService.deleteByIds(carIteamIds.toArray(Integer[]::new));
        }

        return count>0;
    }

    @Override
    public boolean update(Order order) {
        return orderMapper.updateById(order)>0;
    }
    // 发货
    @Override
    public boolean updateForShip(Integer orderId) {
        Order order = orderMapper.selectById(orderId);
        System.out.println(order.getStatus());
        if(order.getStatus().equals("待发货")){
            order.setStatus("待收货");
            order.setShipTime(LocalDateTime.now());
            return orderMapper.updateById(order)>0;
        }
        return false;
    }
    // 确认收货
    @Override
    public boolean updateForAccept(Integer orderId) {
        Order order = orderMapper.selectById(orderId);
        if(order.getStatus().equals("待收货")){
            order.setStatus("已确认");
            order.setAcceptTime(LocalDateTime.now());
            return orderMapper.updateById(order)>0;
        }
        return false;
    }

    // 批量删除
    @Override
    public int deleteByIds(List<Integer> ids, boolean logic) {
        if(logic){
            int count = 0;

            Order order = new Order();
            order.setIsDel(true);
            for(Integer id:ids){
                order.setId(id);
                count += orderMapper.updateById(order);
            }
            return count;
        }else {
            OrderItem oi = new OrderItem();
            for (Integer id:ids){
                oi.setId(id);
                orderItemService.deleteBy(oi);
            }
            return orderMapper.deleteByIds(ids);
        }
    }

    @Override
    public boolean seckill(Order order) {

        Long goodId = order.getOrderItems().get(0).getGoodId();

        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(Long.class);
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("seckill.lua")));
        Long result = redisTemplate.execute(redisScript, List.of(goodId.toString()), order.getMemberAccount());
        if (result <= 0) {//执行秒杀脚本失败
            return false;
        }

        this.rocketMQTemplate.asyncSend("mall-order-topic", order, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                redisTemplate.opsForValue().set("mall-seckill-order:" + order.getMemberAccount() + ":" + goodId, "创建订单消息发送成功");
            }

            @Override
            public void onException(Throwable throwable) {
                redisTemplate.opsForValue().set("mall-seckill-order:" + order.getMemberAccount() + ":" + goodId, "创建订单消息发送失败，请稍候重试");
            }
        });
        return true;
    }

    // 图像数据
    @Override
    public Sales getKeyMetrics(LocalDate startDate, LocalDate endDate) {
        // 处理空值情况，设置默认时间范围
        if (startDate == null || endDate == null) {
            startDate = LocalDate.of(1, 1, 1);
            endDate = LocalDate.of(9999, 1, 31);
        }

        // 查询订单统计数据
        BigDecimal totalSales = orderMapper.getTotalSales(startDate, endDate);
        BigDecimal totalOrders = orderMapper.getTotalOrders(startDate, endDate);
        BigDecimal totalCustomers = orderMapper.getTotalCustomers(startDate, endDate);

        // 计算平均价格，避免除零异常
        BigDecimal avgPrice;
        if (totalOrders != null && totalOrders.compareTo(BigDecimal.ZERO) > 0) {
            avgPrice = totalSales.divide(totalOrders, 2, RoundingMode.HALF_UP);
        } else {
            avgPrice = BigDecimal.ZERO;
        }

        return new Sales(totalSales, totalOrders, totalCustomers, avgPrice);
    }


    @Override
    public List<Map<String, Object>> getPayType(LocalDate startDate, LocalDate endDate) {
        if (startDate == null || endDate == null) {
            endDate = LocalDate.now();
            startDate = endDate.minusDays(30);
        }

        if (endDate.isBefore(startDate)) {
            LocalDate temp = startDate;
            startDate = endDate;
            endDate = temp;
        }

        return orderMapper.getPayTypeStatistics(startDate, endDate);
    }


}
